#!/usr/bin/env python
# -*- coding:utf-8 -*-

import json
import requests
import os
import urllib2
import urlparse
import sqlite3


url        = 'http://120.92.51.248/api/ad/list'
local_db   = "./local.db"
local_path = "./"
video_list = []


# load the config file from the json file.
def load_config():
    try:
        with open('./config.json') as json_file:
            json_data  = json.load(json_file)
            global url
            global local_db
            global local_path

            url        = json_data['remote']['url']
            local_db   = json_data['local']['db_file']
            local_path = json_data['local']['path']
            print url, local_db, local_path
            return True
    except Exception, e:
        print e
    return False


def get_list(local_path):
    try:
        global video_list
        conn = sqlite3.connect(local_db)
        cu   = conn.cursor()

        sql_text = 'select * from ad'
        cu.execute(sql_text)

        reset = cu.fetchall()
        count = len(reset)
        if count>0: 
            for record in reset:
                #print record[0]
                #print record[1]
                #print record[2]
                #print record[3]
                #print record[5]
                video_url = record[3]
                o = urlparse.urlparse(video_url)
                filename = local_path.rstrip('/') + o.path
                video_list.append(filename)

    except Exception, e:
        print e


# play the video file.
def play_file(filename):
    try:
        cmd = "omxplayer %s" % filename
        print cmd
        os.system(cmd)
    except Exception,e:
        print e


def main():
    #load_config()
    #print local_db
    get_list(local_path)
    for video_file in video_list:
        play_file(video_file)


if __name__ == "__main__":
    main()

